package com.cn.lp.export.client.utils;

import com.cn.lp.export.client.base.context.ExportException;
import com.cn.lp.export.client.base.utils.SpringUtils;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Iterator;
import java.util.Map;

/**
 * Description: 请描述你的文件
 *
 * @author wuqirong
 * @date 2020-10-19
 * <p>
 * All rights Reserved, Designed www.xiao100.com
 */
@Component
public class HttpClientAide {

    private static Logger logger = LoggerFactory.getLogger(HttpClientAide.class);

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一：请求Url
     * 参数二：请求的JSON
     * 参数三：请求回调
     */
    public static String postJsonParams(String url, String jsonParams) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
        return execNewCall(request);
    }

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static String get(String url, Map<String, String> queries) {
        StringBuffer sb = getQueryString(url, queries);
        Request request = new Request.Builder()
            .url(sb.toString())
            .build();
        return execNewCall(request);
    }

    /**
     * 根据map获取get请求参数
     *
     * @param queries
     * @return
     */
    public static StringBuffer getQueryString(String url, Map<String, String> queries) {
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        return sb;
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static String post(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        if (!CollectionUtils.isEmpty(params)) {
            //添加参数
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder()
            .url(url)
            .post(builder.build())
            .build();
        return execNewCall(request);
    }

    /**
     * 调用okhttp的newCall方法
     *
     * @param request
     * @return
     */
    private static String execNewCall(Request request) {
        try (Response response = SpringUtils.getBean(OkHttpClient.class)
            .orElseThrow(() -> new ExportException("okHttpClient 未准备好")).newCall(request).execute()) {
            if (response.isSuccessful()) {
                if (response.body() == null) {
                    throw new ExportException("没有消息体");
                } else {
                    return response.body().string();
                }
            } else {
                throw new ExportException("请求异常，异常码：" + response.code());
            }
        } catch (Exception e) {
            throw new ExportException("请求异常，" + ExceptionUtils.getStackTrace(e));
        }
    }

}
